/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package do_.com.pbd.business.referrals.creditcardreferralprogramstatusupdater.impl;

import do_.com.pbd.business.referrals.creditcardreferralprogramstatusupdater.Installer;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.FileUtils;

/**
 *
 * @author Developer
 */
public class NewFilesFinder {
    public static final String backupFolder = "\\backup";
    
    private static final Logger logger = Logger.getLogger(NewFilesFinder.class.getName());

    public List<File> findFiles() throws IOException {

        //Get directory
        String directoryName = Installer.CASES_REPOSITORY;
        File directory = new File(directoryName);
        List<File> filesFound = new ArrayList();

        //Create backup directory
        String backupDirName = directory.getPath() + backupFolder;
        File backupDir = new File(backupDirName);
        if (!backupDir.exists()) {
            backupDir.mkdir();
        }

        //Get files in directory
        String[] fileListInRep = directory.list();
        if (fileListInRep.length > 0) {
            int listLength = fileListInRep.length;
            for (int i = 0; i < listLength; i++) {
                String fn = directoryName + "\\" + fileListInRep[i];
                if (!fn.equals(backupDirName)) {
                    filesFound.add(new File(Installer.CASES_REPOSITORY + "\\" + fileListInRep[i]));
                    //backupFile(fn, backupDirName);
                }
            }
        }

        //Return new files
        return filesFound;
    }

    public void backupFile(List<File> files) {
        logger.log(Level.INFO, "Backing up cases files {0}", files);
        String backupPath = Installer.CASES_REPOSITORY + NewFilesFinder.backupFolder;
        for (File file : files) {
            //String destinationFile = backupPath + "\\" + file.getName();
            try {
                File existingFile = new File(backupPath + "\\" + file.getName());
                if(existingFile.exists()){
                    logger.log(Level.WARNING, "Backup file {0} already exists. Overwriting!", existingFile.getPath());
                    existingFile.delete();
                }
                FileUtils.moveFileToDirectory(file, new File(backupPath), true);
            } catch (IOException ex) {
                Logger.getLogger(NewFilesFinder.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        logger.log(Level.INFO, "Files backed up!");
    }

}
